import { topicApi } from '/api/topic'
import { userApi } from '/api/user'
import { limit } from '/utils/request'

interface PageQuery extends WechatMiniprogram.IAnyObject {
  topicId: string
}

Page({
  data: {
    topicId: 0,
    list: [] as DomoTopicRank[],
    noMore: false,
  },
  onLoad(query: PageQuery) {
    const topicId = +query.topicId
    this.setData({ topicId })
    this.fetchRanks()
  },
  async fetchRanks() {
    const params = { limit }
    let list = await topicApi.getTopicRankUsers(this.data.topicId, params)
    const uids = list.map((i) => i.user_id)
    if (uids.length) {
      const users = await userApi.getUser(uids)
      list = list.map((i) => {
        i.user = users.find((u) => u.id === i.user_id)
        return i
      })
      const noMore = list.length < limit
      this.setData({ list, noMore })
    }
  },
  async onReachBottom() {
    if (this.data.noMore) return
    const params = { limit, offset: this.data.list.length }
    let list = await topicApi.getTopicRankUsers(this.data.topicId, params)
    const uids = list.map((i) => i.user_id)
    if (uids.length) {
      const users = await userApi.getUser(uids)
      list = list.map((i) => {
        i.user = users.find((u) => u.id === i.user_id)
        return i
      })
      const noMore = list.length < limit
      list = [...this.data.list, ...list]
      this.setData({ list, noMore })
    }
  },

  //  进入用户详情
  goUserInfo(e: any) {
    const { user_id } = e.currentTarget.dataset
    wx.navigateTo({
      url: `/mine/homePage/homePage?id=${user_id}`,
    })
  },
})
